<template>
    <div class="app-container">
        <el-form :inline="true" ref="queryRef" class="form-inline" label-position="right" :model="params"
            label-width="200px">
            <el-row justify="center">
                <el-col :span="11">
                    <el-form-item label="业务对象：" class="form-item" prop="type">
                        <el-select v-model="params.type" placeholder="请选择" class="form-select"
                            @change="changeType">
                            <el-option v-for="item in dataTypeInfoArray" :key="item.code" :label="item.name"
                                :value="item.code">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="维护人：" class="form-item" prop="userName">
                        <el-input v-model="params.userName" placeholder="" clearable />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row justify="center">
                <el-col :span="11">
                    <el-form-item label="数据范围：" class="form-item" prop="range">
                        <el-form-item prop="range" style="width: 120px; margin-right: 10px">
                            <el-select v-model="params.range" placeholder="请选择" @change="chooseRange" clearable>
                                <el-option v-for="item in [{ label: '国家级', value: '0' }, { label: '省级', value: '1' }]"
                                    :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="province" style="width: 120px; margin-right: 10px">
                            <el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince" clearable>
                                <el-option key="全国" label="全国" value="全国" v-if="params.range == '0'"></el-option>
                                <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id"
                                    v-if="params.range != '0'">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="city" style="width: 120px; margin-right: 10px">
                            <el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable
                                :disabled="params.range == '0'">
                                <el-option key="全部" label="全部" value="全部"
                                    v-if="params.range == '0' || params.province != ''"></el-option>
                                <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="county" style="width: 120px">
                            <el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty" clearable
                                :disabled="params.range == '0' || params.city == '全部'">
                                <el-option key="全部" label="全部" value="全部"
                                    v-if="params.range == '0' || params.city != ''"></el-option>
                                <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="维护时间：">
                        <el-col :span="11">
                            <el-form-item prop="startTime">
                                <el-date-picker clearable v-model="params.startTime" type="date" placeholder="开始时间"
                                    value-format="YYYY-MM-DD" :disabled-date="startDisableDate" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="1" class="text-center">
                            <span class="text-gray-500">-</span>
                        </el-col>
                        <el-col :span="11">
                            <el-form-item prop="endTime">
                                <el-date-picker clearable v-model="params.endTime" type="date" placeholder="结束时间"
                                    value-format="YYYY-MM-DD" :disabled-date="endDisableDate" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row justify="end">
                <el-form-item class="bottom-button">
                    <el-button type="primary" @click="showUploadDialog = true">导入</el-button>
                    <el-button type="primary" @click="handleEdit">修改</el-button>
                    <el-button type="primary" @click="handleDelete">删除</el-button>
                    <el-button type="primary" @click="onSearch">查询</el-button>
                    <el-button type="primary" @click="onRest">重置</el-button>
                </el-form-item>
            </el-row>
        </el-form>

        <div class="table-wrapper">
            <el-table ref="multipleTableRef" border :data="dataList" style="width: 100%"
                @selection-change="handleSelectionChange" :cell-style="{ border: '1px solid #e5ebf7' }"
                :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column type="index" width="55" label="序号" align="center">
                    <template #default="scope">
                        <span>{{ (params.page - 1) * params.rows + scope.$index + 1 }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="range" header-align="center" align="center" label="数据范围" width="200">
                    <template #default="scope">
                        <span>{{ scope.row.range == '0' ? `国家级` :
                            `省级(${scope.row.provinceName}${scope.row.cityName}${scope.row.countyName})`
                        }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="voltageLevel" header-align="center" align="center" label="电压等级" width="120"
                    v-if="params.type == '7'">
                    <template #default="scope">
                        <span>{{ getName(optionList11, scope.row.voltageLevel) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="structuralStyle" header-align="center" align="center" label="结构形式" width="120"
                    v-if="params.type == '3' || params.type == '4'">
                    <template #default="scope">
                        <span>{{ getName(optionList7, scope.row.structuralStyle) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="siteClassification" header-align="center" align="center" label="场地类别" width="120"
                    v-if="params.type == '1' || params.type == '3'||params.type == '4'|| params.type == '7'">
                    <template #default="scope">
                        <span>{{ getName(optionList1, scope.row.siteClassification) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="type" header-align="center" align="center" label="场地类别" width="120"
                    v-if="params.type == '5'">
                    <template #default="scope">
                        <span>{{ getName(optionList1, scope.row.type) }}</span>
                    </template>
                </el-table-column>
                <template v-if="params.type == '1'">
                    <el-table-column prop="material" header-align="center" align="center" label="管材" width="120">
                        <template #default="scope">
                            <span>{{ getName(optionList2, scope.row.material) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="joint" header-align="center" align="center" label="接口形式" width="120">
                        <template #default="scope">
                            <span>{{ getName(optionList3, scope.row.joint) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="diameter" header-align="center" align="center" label="管径（mm）" width="120" />
                </template>
                <el-table-column prop="poolShape" header-align="center" align="center" label="水池形状" width="120"
                    v-if="params.type == '2'">
                    <template #default="scope">
                        <span>{{ getName(optionList6, scope.row.poolShape) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="type" header-align="center" align="center" label="设备类型" width="120"
                    v-if="params.type == '6'">
                    <template #default="scope">
                        <span>{{ getName(optionList10, scope.row.type) }}</span>
                    </template>
                </el-table-column>
                <template v-if="params.type == '8'">
                    <el-table-column prop="floor" header-align="center" align="center" label="所在楼层" width="120">
                        <template #default="scope">
                            <span>{{ getName(optionList8, scope.row.floor) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="installationSituation" header-align="center" align="center" label="安装情况"
                        width="120">
                        <template #default="scope">
                            <span>{{ getName(optionList9, scope.row.installationSituation) }}</span>
                        </template>
                    </el-table-column>
                </template>
                <el-table-column prop="year" header-align="center" align="center" label="建造年代" width="120"
                    v-if="params.type != '8'">
                    <template #default="scope">
                        <span>{{ getName(optionList4, scope.row.year) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="intensity" header-align="center" align="center" label="设防情况" width="120"
                    v-if="params.type == '1' || params.type == '2' || params.type == '5'">
                    <template #default="scope">
                        <span>{{ getName(optionList5, scope.row.intensity) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="fortification" header-align="center" align="center" label="设防情况" width="120"
                    v-if=" params.type == '4'">
                    <template #default="scope">
                        <span>{{ getName(optionList5, scope.row.fortification) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="disasterRate6State" header-align="center" align="center" label="VI度破坏状态"
                    width="140" />
                <el-table-column prop="disasterRate7State" header-align="center" align="center" label="Ⅶ度破坏状态"
                    width="140" />
                <el-table-column prop="disasterRate8State" header-align="center" align="center" label="Ⅷ度破坏状态"
                    width="140" />
                <el-table-column prop="disasterRate9State" header-align="center" align="center" label="Ⅸ度破坏状态"
                    width="140" />
                <el-table-column prop="disasterRate10State" header-align="center" align="center" label="Ⅹ度破坏状态"
                    width="140" />
                <el-table-column prop="createUserName" header-align="center" align="center" label="维护人" width="160" />
                <el-table-column prop="createTime" header-align="center" align="center" label="维护时间" width="160" />
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="params.page" v-model:limit="params.rows"
                @pagination="getList" />
        </div>
        <!-- 数据导入弹框 -->
        <import-data v-if="showUploadDialog && provinceData.length > 0" v-model="showUploadDialog" ref="uploadDialog"
            :uploadUrl="uploadUrl" :downloadFileName="downloadFileName" @importSuccess="onImport" :types="params.type"
            :isShow="!isAdmin" :provinceData="provinceData" :cityData="cityData">
        </import-data>

        <el-dialog v-model="dialogEdit" title="修改数据" width="800px">
            <p></p>
            <el-table ref="multipleTableRef1" border :data="dataEditList" style="width: 100%"
                :cell-style="{ border: '1px solid #e5ebf7' }"
                :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
                <el-table-column prop="disasterRate6State" header-align="center" align="center" label="VI度破坏状态">
                    <template #default="scope">
                        <el-select v-model="scope.row.disasterRate6State" placeholder="请选择" class="form-select">
                            <el-option v-for="item in disasterRateStateArray" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="disasterRate7State" header-align="center" align="center" label="Ⅶ度破坏状态">
                    <template #default="scope">
                        <el-select v-model="scope.row.disasterRate7State" placeholder="请选择" class="form-select">
                            <el-option v-for="item in disasterRateStateArray" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="disasterRate8State" header-align="center" align="center" label="Ⅷ度破坏状态">
                    <template #default="scope">
                        <el-select v-model="scope.row.disasterRate8State" placeholder="请选择" class="form-select">
                            <el-option v-for="item in disasterRateStateArray" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="disasterRate9State" header-align="center" align="center" label="Ⅸ度破坏状态">
                    <template #default="scope">
                        <el-select v-model="scope.row.disasterRate9State" placeholder="请选择" class="form-select">
                            <el-option v-for="item in disasterRateStateArray" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="disasterRate10State" header-align="center" align="center" label="Ⅹ度破坏状态">
                    <template #default="scope">
                        <el-select v-model="scope.row.disasterRate10State" placeholder="请选择" class="form-select">
                            <el-option v-for="item in disasterRateStateArray" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button size="default" @click="dialogEdit = false">取 消</el-button>
                    <el-button size="default" type="primary" @click="submitUpload">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
// 引入导入弹框
import ImportData from "./components/ImportData";
import { getValidDictItemsByDictCode } from "@/api/map/disasterDataManagement/lifelineSystemInfo.js";
// 引入store
import useUserStore from '@/store/modules/user';
import { ElMessageBox } from 'element-plus'
// 获取pinia
const userStore = useUserStore();
// 引入接口
import {
    getAllList, //查询
    getRole, // 权限
    removeById,// 删除
    updateById, // 修改
} from "@/api/basicLibrary/lifeVulnerability.js";
import { getProvince, getChildArea } from "@/api/system/division";
import { nextTick } from "vue";
// 获取当前实例
const { proxy } = getCurrentInstance();
//数据类型
const dataTypeInfoArray = ref([
    { code: "1", name: "地下管网" },
    { code: "2", name: "水厂水池" },
    { code: "3", name: "燃气-储气罐（柜）" },
    { code: "4", name: "桥梁" },
    { code: "5", name: "道路" },
    { code: "6", name: "变电站高压电器设备" },
    { code: "7", name: "输电线/电缆" },
    { code: "8", name: "通信设备" },
]);
const disasterRateStateArray = ref([
    { label: '基本完好', value: '基本完好' },
    { label: '轻微破坏', value: '轻微破坏' },
    { label: '中等破坏', value: '中等破坏' },
    { label: '严重破坏', value: '严重破坏' },
    { label: '毁坏', value: '毁坏' }])
const isAdmin = ref(true);
// 响应式对象
const data = reactive({
    // 表单参数
    params: {
        province: isAdmin.value ? '' : userStore.provinceId, //省
        city: "", //市
        county: "", //县
        type: "1", //业务对象
        range: '', // 数据范围 0国家级 1省级
        userName: "", // 维护人
        startTime: "", // 维护时间 开始
        endTime: "", // 结束
        page: 1,
        rows: 10,
    },
    dataList: [],
    total: 0,
    loading: false,
});
// 将一个响应式对象转换为一个普通对象
const {
    params,
    dataList,
    total,
    loading,
} = toRefs(data);

// 改变数据范围
const chooseRange = (value) => {
    if (value == '0') {
        params.value.province = '全国';
        params.value.city = '';
        params.value.county = '';
    } else {
        params.value.province = '';
        params.value.city = '';
        params.value.county = '';
    }
}

// 改变业务类型
const changeType = (value) => {
    if (params.value == value) return;
    onSearch()
}

// 行政区划
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
/** 获取省列表 */
function getProvinceData() {
    getProvince().then((response) => {
        if (!isAdmin.value) {
            provinceData.value = response.data.filter(item => item.id == params.value.province)
        } else {
            provinceData.value = response.data;
        }
    });
}
// 选择省份
function chooseProvince(value) {
    params.value.city = null;
    params.value.county = null;
    //   params.value.province = value.name;
    cityData.value = [];
    areaData.value = [];
    if (value == '全国') { return; }
    getChildArea(value).then((response) => {
        cityData.value = response.data;
    });
}
// 选择城市
function chooseCity(value) {
    //   params.value.city = value.name;
    params.value.county = null;
    areaData.value = [];
    if (value == '全部') { return; }
    getChildArea(value).then((response) => {
        areaData.value = response.data;
    });
}
// 选择区县
function chooseCounty(value) {
    //   params.value.county = value.name;
}

// 维护时间可选范围控制
const startDisableDate = (time) => {
    let endDateVal = params.value.endTime;
    if (endDateVal) {
        return time.getTime() > new Date(endDateVal).getTime();
    }
};
const endDisableDate = (time) => {
    let beginDateVal = params.value.startTime;
    if (beginDateVal) {
        return time.getTime() < new Date(beginDateVal).getTime();
    }
};

// 导入弹框是否显示
let showUploadDialog = ref(false);
let downloadFileName = ref('地下管网易损性数据.xlsx')
// 导入数据接口路径
const uploadUrl = ref(`/lifelineFoundationLibrary/upload`);
// 监听业务对象
watch(params.value, (value) => {
    switch (value.type) {
        case '1':
            downloadFileName.value = '地下管网易损性数据.xlsx';
            break;
        case '2':
            downloadFileName.value = '水厂水池易损性数据.xlsx';
            break;
        case '3':
            downloadFileName.value = '燃气储气罐（柜）易损性数据.xlsx';
            break;
        case '4':
            downloadFileName.value = '桥梁易损性数据.xlsx';
            break;
        case '5':
            downloadFileName.value = '道路易损性数据.xlsx';
            break;
        case '6':
            downloadFileName.value = '变电站高压电器设备易损性数据.xlsx';
            break;
        case '7':
            downloadFileName.value = '电线电缆易损性数据.xlsx';
            break;
        case '8':
            downloadFileName.value = '通信设备易损性数据.xlsx';
            break;
        default:
            break;
    }
}, { immediate: true, deep: true })
// 导入数据接口路径
// 导入成功回调
const onImport = (response, uploadFile, uploadFiles) => {
    const { code, data } = response;
    if (code == 200 && data) {
        if (data && data.length > 0) {
            ElMessageBox.confirm(
                `第${data.join('、')}行数据已存在，无法导入`,
                'Warning',
                {
                    confirmButtonText: '确定',
                    type: 'warning',
                }
            )
        }else{
            proxy.$modal.msgSuccess('导入数据成功!');
            // 列表数据回显
            getList()
        }
    }
}

// 修改
const dialogEdit = ref(false);
const dataEditList = ref([])//修改的数据
const handleEdit = () => {
    if (ranges.value.length == 0) {
        proxy.$modal.msgWarning('请勾选要修改的数据！！！')
        return;
    } else {
        if (isAdmin.value) {
            let flag = ranges.value.every(item => item == '0');
            if (!flag) {
                proxy.$modal.msgWarning('只能修改国家级数据！！！');
                return;
            } else {
                getDialogEditData()
            }
        } else {
            let flag = ranges.value.every(item => item == '1');
            if (!flag) {
                proxy.$modal.msgWarning('只能修改省级数据！！！');
                return;
            } else {
                getDialogEditData()
            }
        }
    }
}
const submitUpload = () => {
    updateById(dataEditList.value).then(res => {
        proxy.$modal.msgSuccess('修改成功');
        dialogEdit.value = false;
        getList();
    })
}
const getDialogEditData = () => {
    dataEditList.value = [];
    multipleSelection.value.forEach(item => {
        dataEditList.value.push({
            type: params.value.type,
            id: item.id,
            disasterRate6State: item.disasterRate6State,
            disasterRate7State: item.disasterRate7State,
            disasterRate8State: item.disasterRate8State,
            disasterRate9State: item.disasterRate9State,
            disasterRate10State: item.disasterRate10State,
        })
    });
    dialogEdit.value = true;
}

// 删除
const handleDelete = () => {
    if (ids.value.length == 0) {
        proxy.$modal.msgWarning('请勾选要删除的数据！！！')
        return;
    } else {
        if (isAdmin.value) {
            let flag = ranges.value.every(item => item == '0');
            if (!flag) {
                proxy.$modal.msgWarning('只能删除国家级数据！！！');
                return;
            } else {
                deletes()
            }
        } else {
            let flag = ranges.value.every(item => item == '1');
            if (!flag) {
                proxy.$modal.msgWarning('只能删除省级数据！！！');
                return;
            } else {
                deletes()
            }
        }
    }
}

const deletes = () => {
    proxy.$modal
        .confirm(
            "确定要删除所选中的数据吗？"
        )
        .then(function () {
            return removeById({ ids: ids.value.join(","), type: params.value.type });
        })
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
}

//查询结果多选事件
const multipleSelection = ref([])
const ids = ref([]);
const ranges = ref([]);
function handleSelectionChange(val) {
    multipleSelection.value = val;
    ids.value = val.map(item => item.id);
    ranges.value = val.map(item => item.range);
}

/** 搜索按钮操作 */
function onSearch() {
    params.value.page = 1;
    getList();
}
/** 重置按钮操作 */
function onRest() {
    dataList.value = [];
    proxy.resetForm("queryRef");
    if (!isAdmin.value) {
        params.value.province = userStore.provinceId;

        chooseProvince(params.value.province)
    }
    onSearch();
}

/** 查询数据列表 */
function getList() {
    loading.value = true;
    const query = {
        ...params.value,
        province: params.value.province == '全国' ? '' : params.value.province,
        city: params.value.city == '全部' ? '' : params.value.city,
        county: params.value.county == '全部' ? '' : params.value.county,
    }
    getAllList(query).then(response => {
        dataList.value = response.data.rows;
        total.value = response.data.total;
        nextTick(() => {
            proxy.$refs['multipleTableRef'].clearSelection()
        })
        loading.value = false;
    }).catch(err => {
        dataList.value = [];
        total.value = 0;
        loading.value = false;
    });
}
const getRoleInfo = () => {
    getRole().then(res => {
        isAdmin.value = !Boolean(res.data)
        if (!isAdmin.value) {
            params.value.province = userStore.provinceId;
            chooseProvince(params.value.province)
        }else{
            getList();
        }
    })
}

//字典表查询
const optionList1 = ref([])
const optionList2 = ref([])
const optionList3 = ref([])
const optionList4 = ref([])
const optionList5 = ref([])
const optionList6 = ref([])
const optionList7 = ref([])
const optionList8 = ref([])
const optionList9 = ref([])
const optionList10 = ref([])
const optionList11 = ref([])
/** 获取字典值 */
async function getDictData() {
    await getValidDictItemsByDictCode("smxcdlb").then(response => {
        optionList1.value = response.data; //场地类别
    });
    await getValidDictItemsByDictCode("smxdxgwgc").then(response => {
        optionList2.value = response.data;//管材
    });
    await getValidDictItemsByDictCode("smxdxgwjkxs").then(response => {
        optionList3.value = response.data;//接口形式
    });
    await getValidDictItemsByDictCode("smxjsnd").then(response => {
        optionList4.value = response.data;//建造年代
    });
    await getValidDictItemsByDictCode("smxsfqk").then(response => {
        optionList5.value = response.data;//设防情况
    });
    await getValidDictItemsByDictCode("smxgsscxz").then(response => {
        optionList6.value = response.data;//水池形状
    });
    await getValidDictItemsByDictCode("smxrqjgxs").then(response => {
        optionList7.value = response.data;//结构形式
    });
    await getValidDictItemsByDictCode("smxtxsbszlc").then(response => {
        optionList8.value = response.data;//所在楼层
    });
    await getValidDictItemsByDictCode("smxtxsbazqk").then(response => {
        optionList9.value = response.data;//安装情况
    });
    await getValidDictItemsByDictCode("smxbdzsblx").then(response => {
        optionList10.value = response.data;//设备类型
    });
    await getValidDictItemsByDictCode("smxdlxldydj").then(response => {
        optionList11.value = response.data;//电压等级
    });
}

// 返回字典项值
function getName(arr, code) {
    for (let item of arr) {
        if (item.dictItemCode == code) {
            //字典值
            return item.dictItemName;
        }
    }
}
getDictData();
// 获取省份数据
getProvinceData();
onMounted(() => {
    getRoleInfo();
})
</script>

<style lang="scss" scoped>
.form-inline {
    .el-form-item {
        margin-right: 0;
    }
}

.paging {
    margin: 20px 0;
}</style>
